#encoding:UTF-8
# python3.4 未读
# 依赖库
# xlrd
# xlwt
# requests

import urllib

import urllib.request
import xlrd
import xlwt
import requests
from os.path import join, abspath
DEFAULT_CA_BUNDLE_PATH = join(abspath('.'), 'cacert.pem')
from html.parser import HTMLParser
import copy



from tkinter import *
import tkinter.messagebox
import threadpool

header = ['Gene Symbol','NCBI GeneID','GenBank Accession','NCBI Protein Accession','Species','Coding DNA Length','Gene Description',
                  'Primer Pair 1','Amplicon Size',"Sequence (5' -> 3')",'Length','Tm','Location',
                  'Primer Pair 2', 'Amplicon Size', "Sequence (5' -> 3')", 'Length', 'Tm', 'Location',
                  'Primer Pair 3', 'Amplicon Size', "Sequence (5' -> 3')", 'Length', 'Tm', 'Location']
stus = [header,]

def get_realtime_data(searchBox):
    global stus,header
    print('开始获取',searchBox)
    url = 'https://pga.mgh.harvard.edu/cgi-bin/primerbank/new_search2.cgi'
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    values = {'selectBox': 'NCBI Gene Symbol', 'species': 'Human', 'searchBox':searchBox}
    headers = {'User-Agent': user_agent}
    data = urllib.parse.urlencode(values)
    r = requests.post(url, data=values)
    print(r.text)
    hp = MyHTMLParser(searchBox)
    hp.feed(r.text)
    hp.close()
    print('self.datadict', hp.datadict)
    print('self.tmpPrimer', hp.tmpPrimer)
    print('self.tmpSequence', hp.tmpSequence)
    print('listSequence', hp.listSequence)
    #存入data数据
    mydata = []
    opPri = {}
    for hang in ['F', 'R']:
        print(hang)
        tmpint = 0
        for lie in header:
            tmpint = tmpint + 1
            if tmpint <= 7:
                if lie == 'Gene Symbol':
                    mydata.append(hp.datadict[lie] + '-' + hang)
                else:
                    mydata.append(hp.datadict[lie])
            if tmpint >= 8 and tmpint <= 13:
                opPri = hp.listSequence['Primer Pair 1' + hang]
                mydata.append(opPri[lie])
            if tmpint >= 14 and tmpint <= 19:
                opPri = hp.listSequence['Primer Pair 2' + hang]
                mydata.append(opPri[lie])
            if tmpint >= 20 and tmpint <= 25:
                opPri = hp.listSequence['Primer Pair 3' + hang]
                mydata.append(opPri[lie])
        stus.append(mydata)
        print('mydata', mydata)
        mydata = []
    return r.text

        # v_http_resp = requests.get(v_url)
        # v_result = None
        # if v_http_resp.status_code == requests.codes.ok:
        #     v_result = v_http_resp.text
        # return v_result

class MyHTMLParser(HTMLParser):
    def __init__(self,genesymbol):
        HTMLParser.__init__(self)
        self.tmpCount = 0
        self.links = []
        self.genesymbol = genesymbol
        self.datadict = {'Gene Symbol':self.genesymbol,'NCBI GeneID':'','GenBank Accession':'','NCBI Protein Accession':'',
                         'Species':'','Coding DNA Length':'','Gene Description':'',
                        'Primer':[]}
        print('self.datadict.keys():',self.datadict.keys())
        self.tmpkey = ''
        self.tmplist = self.datadict.keys()
        self.tmpPrimer = {'id':1,'PrimerBank ID':'','Amplicon Size':'', 'Sequence':[]}
        self.iniSequence = {'type':'Forward Primer',"Sequence (5' -> 3')":'','Length':'','Tm':'','Location':''}
        self.tmpSequence = {'type':'Forward Primer',"Sequence (5' -> 3')":'','Length':'','Tm':'','Location':''}
        self.listSequence = {}
        self.stoptmp = 0



    def handle_starttag(self, tag, attrs):
        #print "Encountered the beginning of a %s tag" % tag
        if tag == "tr":
            if len(attrs) == 0:
                pass
            else:
                print("dict(attrs)",dict(attrs))
                for (variable, value) in attrs:
                    self.links.append(value)
                    if variable == "href":
                        self.links.append(value)

    def handle_data(self, data):
        if self.stoptmp == 1:
            pass
        if data.strip() != '':
            self.tmpCount = self.tmpCount + 1
            print(self.tmpCount,"Data:", data.strip())
            if self.tmpkey != '' and data.strip() not in self.tmplist and (self.tmpkey in self.tmplist or self.tmpkey in ['Sequence']):
                if 'Gene Description' in self.tmplist:
                    self.datadict[self.tmpkey]=data.strip()
                if 'Amplicon Size' in self.tmplist:
                    self.tmpPrimer[self.tmpkey]=data.strip()
                    print('self.tmpPrimer[self.tmpkey]',self.tmpPrimer[self.tmpkey])
                if 'Location' in self.tmplist:
                    if data.strip() in ['Forward Primer','Reverse Primer']:
                        self.tmpSequence['type']=data.strip()
                    if data.strip() not in ['Forward Primer','Reverse Primer','Sequence',"(5'",'-',"3')",'Location']:
                        if self.tmpCount in [80,32,37,56,61,85]:
                            self.tmpSequence["Sequence (5' -> 3')"]=data.strip()
                        if self.tmpCount in [81,33,38,57,62,86]:
                            self.tmpSequence['Length'] = data.strip()
                        if self.tmpCount in [82,34,39,58,63,87]:
                            self.tmpSequence['Tm'] = data.strip()
                        if self.tmpCount in [35,40,59,64,83,88]:
                            tmpid = 1
                            if self.tmpCount in [59,64]:
                                tmpid = 2
                            if self.tmpCount in [83,88]:
                                tmpid = 3

                            self.tmpSequence['Location'] = data.strip()
                            self.tmpSequence['Primer Pair '+str(tmpid)] = self.tmpPrimer['PrimerBank ID']
                            self.tmpSequence['Amplicon Size'] = self.tmpPrimer['Amplicon Size']
                            print('self.tmpSequence',self.tmpSequence)

                            self.listSequence['Primer Pair '+str(tmpid)+self.tmpSequence['type'][0:1]]=copy.deepcopy(self.tmpSequence)
                            self.tmpSequence = copy.deepcopy(self.iniSequence)
                            #Primer层再替换 123
                            if self.tmpCount in [40,64,88]:
                                self.tmplist = self.tmpPrimer.keys()


                if self.tmpkey == 'Gene Description' and self.datadict[self.tmpkey] != '':
                    #最外层解析完毕，进入里层
                    self.tmplist = self.tmpPrimer.keys()
                if self.tmpkey == 'Amplicon Size' : #and self.tmpPrimer[self.tmpkey] != ''
                    #Primer最外层解析完毕，进入里层
                    self.tmplist = ['Location']
                # if 'Location' == self.tmpkey  and self.tmpSequence[self.tmpkey] != '':
                #     self.stoptmp = 1
            if data.strip() in self.tmplist:
                self.tmpkey = data.strip()
            else:
                self.tmpkey == ''
            # print('self.datadict:',self.datadict)



class MainWindow:

    def buttonListener1(self, event):
        worksheet = xlrd.open_workbook('导入.xlsx')  # 打开excel文件
        sheet_names = worksheet.sheet_names()  # 获取excel中所有工作表名
        sheet2 = worksheet.sheet_by_name('工作表1')  # 根据Sheet名获取数据
        nrows = sheet2.nrows  # 行数
        ncols = sheet2.ncols  # 列数
        num = 0
        for x in range(0, nrows):
            for y in range(0, ncols):
                value = sheet2.cell(x, y).value
                print(sheet2.cell(x, y).value)
                if value == 'Gene Symbol':
                    continue
                self.bhlist.append(value)
                num = num +1
        tkinter.messagebox.showinfo("成功提醒", "导入"+str(num)+"条完成，请点解析开始抓取数据")

    def buttonListener2(self, event):
        print('开始解析')
        self.tmpGeneSymbol = 'SLC5A5'
        '''
        url = 'https://pga.mgh.harvard.edu/cgi-bin/primerbank/new_search2.cgi'

        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'

        values = {'selectBox': 'NCBI Gene Symbol','species':'Human','searchBox':'SLC5A5'}

        headers = {'User-Agent': user_agent}

        data = urllib.parse.urlencode(values)

        r = requests.post(url, data=values)

        print(r.text)
        '''

        # v_index_array = ['SLC5A5', 'EGR1']
        v_index_array = self.bhlist
        v_thread_pool = threadpool.ThreadPool(len(v_index_array))
        requests = threadpool.makeRequests(get_realtime_data, v_index_array)
        [v_thread_pool.putRequest(req) for req in requests]
        v_thread_pool.wait()

        global stus, header
        print('stus',stus)

        book = xlwt.Workbook()  # 新建一个excel
        sheet = book.add_sheet('工作表1')  # 添加一个sheet页
        row = 0  # 控制行
        for stu in stus:
            col = 0  # 控制列
            for s in stu:  # 再循环里面list的值，每一列
                sheet.write(row, col, s)
                col += 1
            row += 1
        book.save('导出.xls')  # 保存到当前目录下
        tkinter.messagebox.showinfo("成功提醒", "完成解析")

    def buttonListener3(self, event):
        tkinter.messagebox.showinfo("messagebox", "this is button 3 dialog")

    def buttonListener4(self, event):
        tkinter.messagebox.showinfo("messagebox", "this is button 4 dialog")

    def __init__(self):

        self.bhlist = []
        self.tmpGeneSymbol=''
        self.frame = Tk()
        self.frame.title(u'qPCR引物序列自动下载软件 版本号: 0.1')

        self.button1 = Button(self.frame, text="导入", width=15, height=1)
        self.button2 = Button(self.frame, text="解析", width=15, height=1)

        # self.button1.grid(row=0, column=5, padx=5, pady=5)
        # self.button2.grid(row=0, column=7, padx=5, pady=5)
        self.button1.pack(pady=10)
        self.button2.pack()

        import datetime
        # 以当前时间作为起始点，days=-7向前偏移7天，days=7向后偏移7天
        time_now = datetime.datetime.now()
        time = (time_now + datetime.timedelta(days=7)).strftime("%Y%m%d")
        print(time)

        self.button1.bind("<ButtonRelease-1>", self.buttonListener1)
        self.button2.bind("<ButtonRelease-1>", self.buttonListener2)
        font = ('Arial', 21)
        self.L1 = Label(self.frame,
                        text='欢迎使用',
                        height=3,
                        anchor='e',
                        font=font
                        ).pack(side=BOTTOM)
        # self.L1.grid(row=1, column=0, columnspan=2)



        sw = self.frame.winfo_screenwidth()
        sh = self.frame.winfo_screenheight()

        # 得到屏幕高度

        ww = 412

        wh = 136

        # 窗口宽高为100

        x = (sw - ww) / 2

        y = (sh - wh) / 2

        self.frame.geometry("%dx%d+%d+%d" % (ww, wh, x, y))

        sh = self.frame.winfo_screenheight()
        self.frame.mainloop()



window = MainWindow()
